/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AnalizadorLex.java
 *
 * Created on 06-dic-2011, 17:40:56
 */
package es.plg.trad.analizador;

import es.plg.trad.analizador.main.AnalizadorMain;
import es.plg.trad.utils.PintaFondo;
import es.plg.traductor.main.Traductor;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.ComponentUI;

/**
 *
 * @author hp
 */
public class AnalizadorLex extends javax.swing.JInternalFrame {

    private static final long serialVersionUID = 1L;
    /** Creates new form AnalizadorLex */
    private String ruta;
    private File ficheroEnt;
    private File FicheroAux;

    public AnalizadorLex() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setClosable(true);
        setForeground(java.awt.Color.cyan);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Analizador Léxico");
        setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/es/plg/trad/resources/images/pasc_c.png"))); // NOI18N
        setInheritsPopupMenu(true);
        setOpaque(true);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 51, 204));
        jLabel1.setText("Código Pascal De Entrada");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 51, 204));
        jLabel2.setText("Definición de los tokens De Salida");
        jLabel2.setName("jLabel2"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextArea2.setColumns(20);
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(5);
        jTextArea2.setName("jTextArea2"); // NOI18N
        jTextArea2.setEditable(false);
        jScrollPane2.setViewportView(jTextArea2);

        jButton1.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jButton1.setForeground(new java.awt.Color(0, 102, 51));
        jButton1.setText("Cargar Fichero");
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jButton2.setForeground(new java.awt.Color(0, 102, 51));
        jButton2.setText("Analizar");
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jButton3.setForeground(new java.awt.Color(0, 102, 51));
        jButton3.setText("Refrescar");
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTextPane1.setName("jTextPane1"); // NOI18N
        jScrollPane3.setViewportView(jTextPane1);
        try{
            this.setBorder(new PintaFondo());
        } catch(MalformedURLException e){

        } catch(IOException e){

        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton2))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 501, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane3))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(259, 259, 259)
                                .addComponent(jButton3))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(163, 163, 163)
                        .addComponent(jLabel1)
                        .addGap(202, 202, 202)
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton3)
                        .addComponent(jButton2)))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription("Analizador Léxico");

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {
        // TODO add your handling code here:
        abreYLeeFichero();
    } catch (IOException ex) {
        Logger.getLogger(AnalizadorMain.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {
        // TODO add your handling code here:
        analizarCodigoPascal();
    } catch (IOException ex) {
        Logger.getLogger(AnalizadorLex.class.getName()).log(Level.SEVERE, null, ex);
    }

}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
    this.jTextPane1.selectAll();
    this.jTextPane1.cut();
    jButton2ActionPerformed(evt);
}//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

    public JButton getjButton1() {
        return jButton1;
    }

    public void setjButton1(JButton jButton1) {
        this.jButton1 = jButton1;
    }

    public JButton getjButton2() {
        return jButton2;
    }

    public void setjButton2(JButton jButton2) {
        this.jButton2 = jButton2;
    }

    public JButton getjButton3() {
        return jButton3;
    }

    public void setjButton3(JButton jButton3) {
        this.jButton3 = jButton3;
    }

    public JLabel getjLabel1() {
        return jLabel1;
    }

    public void setjLabel1(JLabel jLabel1) {
        this.jLabel1 = jLabel1;
    }

    public JLabel getjLabel2() {
        return jLabel2;
    }

    public void setjLabel2(JLabel jLabel2) {
        this.jLabel2 = jLabel2;
    }
//
//    public JScrollPane getjScrollPane1() {
//        return jScrollPane1;
//    }
//
//    public void setjScrollPane1(JScrollPane jScrollPane1) {
//        this.jScrollPane1 = jScrollPane1;
//    }

    public JScrollPane getjScrollPane2() {
        return jScrollPane2;
    }

    public void setjScrollPane2(JScrollPane jScrollPane2) {
        this.jScrollPane2 = jScrollPane2;
    }

//    public JTextArea getjTextArea1() {
//        return jTextArea1;
//    }
//
//    public void setjTextArea1(JTextArea jTextArea1) {
//        this.jTextArea1 = jTextArea1;
//    }
    public JTextArea getjTextArea2() {
        return jTextArea2;
    }

    public void setjTextArea2(JTextArea jTextArea2) {
        this.jTextArea2 = jTextArea2;
    }

    public String getRuta() {
        return ruta;
    }

    public void setRuta(String ruta) {
        this.ruta = ruta;
    }

    public boolean isIconable() {
        return iconable;
    }

    public void setIconable(boolean iconable) {
        this.iconable = iconable;
    }

    public boolean isIsClosed() {
        return isClosed;
    }

    public void setIsClosed(boolean isClosed) {
        this.isClosed = isClosed;
    }

    public boolean isIsIcon() {
        return isIcon;
    }

    public void setIsIcon(boolean isIcon) {
        this.isIcon = isIcon;
    }

    public boolean isIsMaximum() {
        return isMaximum;
    }

    public void setIsMaximum(boolean isMaximum) {
        this.isMaximum = isMaximum;
    }

    public boolean isIsSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

    public EventListenerList getListenerList() {
        return listenerList;
    }

    public void setListenerList(EventListenerList listenerList) {
        this.listenerList = listenerList;
    }

    public ComponentUI getUi() {
        return ui;
    }

    public void setUi(ComponentUI ui) {
        this.ui = ui;
    }

    public File getFicheroAux() {
        return FicheroAux;
    }

    public void setFicheroAux(File FicheroAux) {
        this.FicheroAux = FicheroAux;
    }

    public File getFicheroEnt() {
        return ficheroEnt;
    }

    public void setFicheroEnt(File ficheroEnt) {
        this.ficheroEnt = ficheroEnt;
    }

    private void abreYLeeFichero() throws FileNotFoundException, IOException {
        JFileChooser jfch = new JFileChooser();
        FileFilter filt = new FileNameExtensionFilter("Pascal source file", new String[]{"pas", "inc"});
        jfch.setFileFilter(filt);
        this.add(jfch);
        jfch.setSize(250,450);
        jfch.setName("Buscar fichero Pascal");
        jfch.showOpenDialog(this);
        jfch.setVisible(true);
        ruta = jfch.getSelectedFile().getAbsolutePath();
        //File f = new File(ruta);
        ficheroEnt = jfch.getSelectedFile();
        setToolTipText("Analisis L�xico de: "+ficheroEnt.getAbsolutePath());
        setTitle(this.getTitle() +" de: "+ ficheroEnt.getName());
        leeFichero(ficheroEnt);
    }

    private void leeFichero(File f) throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        StringBuilder lineaTotal = new StringBuilder();
        String linea = reader.readLine();
        while (linea != null) {
            lineaTotal.append(linea);
            lineaTotal.append(System.getProperty("line.separator"));
            linea = reader.readLine();
        }
        jTextArea2.setText(lineaTotal.toString());
        reader.close();
    }

    private void analizarCodigoPascal() throws IOException {

        Traductor tr = new Traductor();
        List<String> ls = new ArrayList<String>();
        ls = tr.AnalizaTokens(ficheroEnt.getAbsolutePath());
        StringBuilder s = new StringBuilder();
        jTextPane1.setContentType("text/html");
        for(int i = 0; i<ls.size();i++){
            if(ls.get(i).toString().startsWith("ERROR")){
                s.append("<font color=red><b>").append(ls.get(i).toString()).append("<b></font>");
                s.append("<HR>");
            } else {
               s.append(ls.get(i).toString());
               s.append("<HR>"); 
            }
            
        }
//        StringTokenizer tk = new StringTokenizer(salida, "["); // Cambia aquí el separador
        
//        while (tk.hasMoreTokens()) {
//            //System.out.println(tk.nextToken());
//            if(tk.nextToken().startsWith("ERROR")){
//                s.append("<font color=blue>").append(tk.nextToken()).append("</font>");
//            }
//            s.append(tk.nextToken().toString());
//        }
       
        //jTextArea1.setText(Salida);
        jTextPane1.setText(s.toString());
    }
}